package spring.yongongsystem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spring.yongongsystem.POJO.dto.CategoryPageQueryDTO;
import spring.yongongsystem.POJO.entity.Category;
import spring.yongongsystem.exception.DeletionNotAllowedException;
import spring.yongongsystem.mapper.CategoryMapper;
import spring.yongongsystem.mapper.ProductMapper;
import spring.yongongsystem.result.PageResult;
import spring.yongongsystem.service.CategoryService;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;
    @Override
    public void save(Category category) {
        categoryMapper.insert(category);
    }

    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO);

        long total = categoryMapper.count();
        return new PageResult(total, page.getResult());
    }

    @Override
    public void deleteById(Long id) {
        //查询当前分类是否关联了产品，如果关联了就抛出业务异常
        Integer count = productMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有产品，不能删除
            throw new DeletionNotAllowedException("当前分类关联了产品，不能删除");
        }
        //删除分类数据
        categoryMapper.deleteById(id);
    }

    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }
}
